#include "messagesession.h"
#include <QCoreApplication>
#include <gloox/message.h>
#include <gloox/messagesession.h>

MessageSession::MessageSession(gloox::MessageSession* _session)
    :eventHandler(NULL)
{
    session = _session;

}

void MessageSession::setEventHandler(QObject* handler)
{
    eventHandler = handler;
    session->registerMessageHandler(this);
}

void MessageSession::close()
{
    session->removeMessageHandler();
    XmppManager::instance().closeSession(session);
}


void MessageSession::send(QString message)
{
    std::string msg = message.toUtf8().constData();
    session->send(msg);
}

void 	MessageSession::handleMessage (const gloox::Message &msg,
                                        gloox::MessageSession *session)
{

    if (eventHandler)
    {
        MessageEvent* event = new MessageEvent;
        event->messageItem().setMessage(QString::fromUtf8(msg.body().c_str()));
        event->messageItem().setJid(session->target().bare().c_str());
        event->messageItem().setTimeStamp(QDateTime::currentDateTime());
        QCoreApplication::postEvent(eventHandler, event);
    }


}

void 	MessageSession::handleMessageEvent (const gloox::JID &from, gloox::MessageEventType event)
{
}

void 	MessageSession::handleChatState (const gloox::JID &from, gloox::ChatStateType state)
{

}
